<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\Tools\AliOss;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;

class UploadController extends Controller {

    /**
     * 上传临时文件
     * @param Request $request
     */
    function index(Request $request){
        $img = 'file';

        //读取file
        $file = $request->file('file');
        if(is_null($file)){
            $img = 'img';
            $file = $request->file('img');
        }

        //验证文件大小，不超过500kb
        $fileSize=$file->getSize();
        if($fileSize>512000){
            return $this->setReturnJson(-1,'文件过大，请不要上传超过500KB的图片',['file_name'=>$file->getClientOriginalName()]);
        }
        //验证文件格式，仅支持jpg或png
        $fileExtension=$file->getClientOriginalExtension();
        if(!in_array($fileExtension,['jpg','jpeg','png'])){
            return $this->setReturnJson(-1,'仅支持上传jpg/png格式的文件',['file_name'=>$file->getClientOriginalName()]);
        }

        //保存到临时文件夹 并根据日期临时存储 todo 定期清空
        if($img === 'file'){
            $date = date('Y-m-d');
            $name = Storage::put('public/tmp/images/'.$date,$file);
        } else {
            $name = Storage::put('public/images/article',$file);
            $object = substr($name,7);
            $filePath = 'storage'.substr($name,6);
            $result = AliOss::uploadFile($object, $filePath);
            if(!$result){
                return $this->setReturnJson(-1,'uploadFailed');
            }
        }


        return $this->setReturnJson(0,'success',['tmp_file_name'=>$name]);

    }


}
